package br.com.sipsoft.svola.persistence;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

import org.apache.log4j.Logger;
import org.hibernate.Session;
import org.hibernate.StatelessSession;

public class HibernateUtils {

	private static final HibernateUtils instancia = new HibernateUtils();
	private static final Logger log = Logger.getLogger(HibernateUtils.class);

	private EntityManagerFactory factory;
	private ThreadLocal<EntityManager> threadLocal = new ThreadLocal<EntityManager>();;
	
	private HibernateUtils(){
		
	}

	public StatelessSession openStatelessSession(){
		return ((Session)getCurrentEntityManager().getDelegate()).getSessionFactory().openStatelessSession();
	}

	public static HibernateUtils getInstancia(){
		return instancia;
	}

	public void iniciaFabrica(String unitPersistence){
		factory = Persistence.createEntityManagerFactory(unitPersistence);
	}

	public EntityManager getCurrentEntityManager(){
		EntityManager manager = threadLocal.get();
		if(manager == null){
			manager = openEntityManager();
			threadLocal.set(manager);
		}
		return threadLocal.get();
	}

	private EntityManager openEntityManager() {
		return factory.createEntityManager();
	}

	public void beginTransaction(){
		log.info("#####	Initializing transaction #######");
		getCurrentEntityManager().getTransaction().begin();
	}

	public void commitTransaction(){
		log.info("#####	Commiting transaction #######");
		getCurrentEntityManager().flush();
		getCurrentEntityManager().getTransaction().commit();
	}

	public void rollbackTransaction(){
		if(getCurrentEntityManager().getTransaction().isActive()){
			log.info("#####	Rollbacking transaction #######");
			getCurrentEntityManager().getTransaction().rollback();
		}
	}

	public void fechaFabrica(){
		factory.close();
	}

	public void save(Object obj){
		beginTransaction();
		getCurrentEntityManager().persist(obj);
	}

	public void saveWithoutSession(Object obj){
		StatelessSession ses = openStatelessSession();
		//ses.getTransaction().begin();
		ses.insert(obj);
		//ses.getTransaction().commit();	
	}
	
	public void deleteWithoutSession(Object obj){
		StatelessSession ses = openStatelessSession();
		ses.getTransaction().begin();
		ses.delete(obj);
		ses.getTransaction().commit();		
	}
}
